import 'package:flutter/material.dart';
import 'package:flutter_food_ordering_web/model/cart_model.dart';
import 'package:flutter_food_ordering_web/res/colors.dart';
import 'package:flutter_food_ordering_web/res/dimens.dart';
import 'package:flutter_food_ordering_web/res/styles.dart';
import 'package:flutter_food_ordering_web/widget/centered_view.dart';
import 'package:flutter_food_ordering_web/widget/checkout_page_navigation_bar.dart';
import 'package:flutter_food_ordering_web/widget/my_checkbox.dart';
import 'package:flutter_food_ordering_web/widget/my_dialog.dart';
import 'package:flutter_food_ordering_web/widget/my_take_food_dialog.dart';
import 'package:provider/provider.dart';

class CheckoutPage extends StatefulWidget {
  CheckoutPage({Key key}) : super(key: key);

  @override
  _CheckoutPageState createState() => _CheckoutPageState();
}

class _CheckoutPageState extends State<CheckoutPage> {
  @override
  Widget build(BuildContext context) {
    
    var cart = Provider.of<Cart>(context);
    selectedChanged(cart);

    return Scaffold(
      body: CenteredView(
        child: Column(
          children: <Widget>[
            CheckoutPageNavigationBar(),
            Container(
              alignment: Alignment.topLeft,
              padding: const EdgeInsets.only(left: 120, top: 31.5),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text('全部美食',
                    style: TextStyle(
                      fontSize: Dimens.font_sp14,
                      color: Color(0xffc41319)
                    ),
                  ),
                  SizedBox(height: 2),
                  Container(
                    width: 72.5,
                    height: 1,
                    color: Color(0xffcd2d33),
                  )
                ],
              ),
            ),
            _buildListHead(cart),
            _buildCartItemList(cart),
            _buildCartCheckoutBar(cart)
          ]
        )
      )
    );
  }

  bool _allChecked = true;

  Widget _buildListHead(Cart cart) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 120),
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 15),
        color: Color(0xfff3f3f3),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            MyCheckBox(
              isChecked: _allChecked,
              onPressed: (bool oldVal) {
                setState(() {
                  _allChecked = !_allChecked;

                selectedAllItems(cart, _allChecked);
                });
              },
            ),
            SizedBox(width: 12.5),
            Container(
              width: 58.5,
              child: Text('全选', style: TextStyles.textDark9W600,
              ),
            ),
            Flexible(
              flex: 5,
              fit: FlexFit.tight,
              child: Padding(
                padding: const EdgeInsets.only(left: 40.5),
                child: Text('美食', style: TextStyles.textDark9W600),
              )
            ),
            Flexible(
              flex: 1,
              fit: FlexFit.tight,
              child: Text('单价', textAlign: TextAlign.center, style: TextStyles.textDark9W600),
            ),
            Flexible(
              flex: 2,
              fit: FlexFit.tight,
              child: Text('数量', textAlign: TextAlign.center, style: TextStyles.textDark9W600),
            ),
            Flexible(
              flex: 1,
              fit: FlexFit.tight,
              child: Text('小记', textAlign: TextAlign.center, style: TextStyles.textDark9W600),
            ),
            Flexible(
              flex: 1,
              fit: FlexFit.tight,
              child: Text('操作', textAlign: TextAlign.center, style: TextStyles.textDark9W600),
            )
          ],
        ),
      ),
    );
  }

  Widget _buildCartItemList(Cart cart) {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 120),
        child: Scrollbar(
          child: ListView.builder(
            itemCount: cart.cartItems.length,
            shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
              return _buildCartItem(cart, cart.cartItems[index]);
            }
          )
        ),
      )
    );
  }

  Widget _buildCartItem(Cart cart, CartModel cartModel) {
    return Container(
      margin: const EdgeInsets.only(top: 15.5),
      padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 15),
      decoration: BoxDecoration(
        border: Border(top: BorderSide(color: Color(0xffaaaaaa), width: 1)),
        color: Color(0x319ece37)
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          MyCheckBox(
            isChecked: cartModel.selected,
            onPressed: (bool oldVal) {
              setState(() {
                cartModel.selected = !cartModel.selected;

                selectedChanged(cart);
              });
            },
          ),
          SizedBox(width: 12.5),
          Image.network(
            cartModel.food.image,
            fit: BoxFit.fill,
            width: 58.5,
            height: 58.5,
            loadingBuilder: (context, Widget child, ImageChunkEvent progress) {
              if (progress == null) return child;
              return Padding(
                  padding: EdgeInsets.all(32),
                  child: CircularProgressIndicator(
                    value: progress.expectedTotalBytes != null ? progress.cumulativeBytesLoaded / progress.expectedTotalBytes : null,
                  ));
            },
          ),
          Flexible(
            flex: 5,
            fit: FlexFit.tight,
            child: Padding(
              padding: const EdgeInsets.only(left: 27),
              child: Text(cartModel.food.name, style: TextStyles.textDark9W600),
            )
          ),
          Flexible(
            flex: 1,
            fit: FlexFit.tight,
            child: Text('¥${cartModel.food.price}', textAlign: TextAlign.center, style: TextStyles.textDark9W600),
          ),
          Flexible(
            flex: 2,
            fit: FlexFit.tight,
            child: Text('${cartModel.quantity}', textAlign: TextAlign.center, style: TextStyles.textDark9W600),
          ),
          Flexible(
            flex: 1,
            fit: FlexFit.tight,
            child: Text('¥${cartModel.food.price * cartModel.quantity}', textAlign: TextAlign.center, style: TextStyles.textDark9W600),
          ),
          Flexible(
            flex: 1,
            fit: FlexFit.tight,
            child: InkWell(
              onTap: () {

              },
              child: Text('删除', textAlign: TextAlign.center, style: TextStyles.textDark9W600),
            ),
          )
        ],
      ),
    );
  }

  //选择菜品的种类
  int selectedTypeCount = 0;
  //结算已选择的菜品的总价格
  double totalPrice = 0.00;

  Widget _buildCartCheckoutBar(Cart cart) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 120),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [BoxShadow(color: Color(0x2b000000), offset: Offset(0, -2), blurRadius: 2.0, spreadRadius: 0)],
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          SizedBox(width: 15),
          MyCheckBox(
            isChecked: _allChecked,
            onPressed: (bool oldVal) {
              setState(() {
                _allChecked = !_allChecked;

                selectedAllItems(cart, _allChecked);
              });
            },
          ),
          SizedBox(width: 12.5),
          Text('全选', style: TextStyles.textDark9W600,),
          SizedBox(width: 17.5),
          InkWell(
            onTap: () {

            },
            child: Text('删除选中美食 移出餐车', style: TextStyles.textGray10,),
          ),
          SizedBox(width: 10),
          InkWell(
            onTap: () {

            },
            child: Text('清理餐车', style: TextStyles.textDark11W600,),
          ),
          Expanded(
            child: RichText(
              textAlign: TextAlign.right,
              text: TextSpan(
                text: '已选择',
                style: TextStyles.textGray10,
                children: <TextSpan>[
                  TextSpan(
                    text: '$selectedTypeCount',
                    style: TextStyle(color: Color(0xfff0580c))
                  ),
                  TextSpan(
                    text: '样美食',
                    style: TextStyles.textGray10
                  )
                ]
              ),
            )
          ),
          SizedBox(width: 33),
          RichText(
            text: TextSpan(
              text: '总价：',
              style: TextStyles.textGray10,
              children: <TextSpan>[
                TextSpan(
                  text: '¥$totalPrice',
                  style: TextStyle(
                    fontSize: 13,
                    color: Color(0xfff0580c)
                  )
                )
              ]
            ),
          ),
          SizedBox(width: 16),
          InkWell(
            onTap: () {
              if(selectedTypeCount > 0) {
                showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (BuildContext context) {
                    return MyDialog(
                      title: '温馨提示',
                      content: '您好！！将为您结算餐车内美食。',
                      okText: '确定',
                      cancelText: '取消',
                      onPressed: (isOk) {
                        //去领餐二维码
                        if(isOk) {
                          showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (BuildContext context) {
                              return MyTakeFoodDialog(
                                data: '7758258',
                                number: '8866',
                              );
                            }
                          );
                        }
                      },
                    );
                  }
                );
              } else {
                showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (BuildContext context) {
                    return MyDialog(
                      title: '温馨提示',
                      content: '请先选择餐车内美食信息',
                      okText: '确定',
                      cancelText: '取消',
                      onPressed: (isOk) {
                        
                      },
                    );
                  }
                );
              }
            },
            child: Container(
              width: 74.5,
              height: 37.5,
              color: selectedTypeCount > 0 ? Color(0xffff7f00) : Colours.text_dark,
              child: Center(
                child: Text('去结算',
                  style: TextStyle(
                    fontSize: Dimens.font_sp14,
                    color: Colors.white
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void selectedAllItems(Cart cart, bool allSelected) {
    for (CartModel cartModel in cart.cartItems) {
      cartModel.selected = allSelected ? true : false;
    }

    selectedChanged(cart);
  }

  void selectedChanged(Cart cart) {
    int count = 0;
    double total = 0;
    for (CartModel cartModel in cart.cartItems) {
      if (cartModel.selected) {
        count++;
        total += cartModel.food.price * cartModel.quantity;
      }
    }
    setState(() {
      selectedTypeCount = count;
      totalPrice = total;
    });
  }
}